//
//  NvEditTrimViewController.m
//  NvSellerShow
//
//  Created by Meicam on 2017/4/5.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvEditTrimViewController.h"

#import "NvWindowPlayer.h"
#import "ControllView.h"
#import "SAVideoRangeSlider.h"

#import "MediaModel.h"
#import "NvMakeFilmClipModel.h"
#import "SaSliderModel.h"

#import "NvsVideoClip.h"
#import "NvsVideoTrack.h"
#import "NvCapationStyleCell.h"
#import "NvPlaySlider.h"
#import "DCSliderView.h"

@interface NvEditTrimViewController ()<ControllViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,NvsStreamingContextDelegate,ShapeViewDelegate> {
    NSNumber* _audioVolumn;
    int _time;
    NSNumber *_defaultTrinIn, *_defaultTrimOut;//传进来的默认trimin，trimout值
}
//timeline相关
@property (strong, nonatomic) NvsTimeline *timeline;
@property (nonatomic, strong) NvsVideoClip * nvsVideoClip;

@property (weak, nonatomic) IBOutlet NvsLiveWindow *liveWindow;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UILabel *curLabel;
@property (weak, nonatomic) IBOutlet UILabel *durationLabel;
@property (weak, nonatomic) IBOutlet NvPlaySlider *progressSlider;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *liveWindowConstraint1v1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *liveWindowConstraint16v9;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *liveWindowConstraint9v16;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *liveWindowConstraintLeft;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *liveWindowConstraintTop;



//试图相关
@property (strong, nonatomic) UIView *selectView;
@property (nonatomic,assign) NSInteger lastBtnTag;
@property (strong, nonatomic) ControllView *controllView;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UIView *speedGoverningView;

@property (strong, nonatomic) UIView *bottomView;

@property (strong, nonatomic) NSMutableArray *filterArray;

@property (nonatomic, assign) int64_t playStart;
@property (nonatomic, assign) int64_t playEnd;
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, strong) NSTimer *playbackProgressTimer;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;

@property (nonatomic, strong) NvsTimelineVideoFx *curVideoFx;

@end

@implementation NvEditTrimViewController {
    bool _isVideoEdit;//编辑状态
    bool _isVideoFast;//快速状态
    bool _isVideoFilter;//滤镜状态
    
    NSMutableString *_fxTestPackageId;
    NSMutableString *_fxPackageId;
    
    CGFloat videoSpeed;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    
    _isVideoFilter = true;
    _isVideoEdit = false;
    _isVideoFast = false;
    //初始化数据
    [self nv_buildTimeLine];
    [self nv_getDefaultTrimTimeRange];
    
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    self.streamingContext.delegate = self;
    
    if(self.nvsVideoClip) {
        self.playStart = self.nvsVideoClip.inPoint;
        self.playEnd = self.nvsVideoClip.outPoint;
    }
    self.progressSlider.value = 0;
    self.lastBtnTag = 100;
    
    [self.view addSubview:self.selectView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.controllView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.speedGoverningView];
    [self.progressSlider addTarget:self action:@selector(progressSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self createControllView];
    [self initNavigationBarView];
    [self initSubViews];
    [self registerCaptionStyleCollectionViewCell];
    [self setDefaultData];
    [self seekTimeline];
}

- (void)initSubViews {
    [self fitLiveWindowHeight];
    [self updateCurLabel];
    [self updateDurationLabel];
    if (_isVideoEdit) {
        [self onShapeViewDelegateEventWithString:@"1"];
        [self.controllView setHidden:NO];
        [self.collectionView setHidden:YES];
        [self.speedGoverningView setHidden:YES];
    } else if (_isVideoFilter){
        [self.collectionView setHidden:NO];
        [self.controllView setHidden:YES];
        [self.speedGoverningView setHidden:YES];
    } else {
        [self onShapeViewDelegateEventWithString:[NSString stringWithFormat:@"%g",videoSpeed]];
        [self.speedGoverningView setHidden:NO];
        [self.controllView setHidden:YES];
        [self.collectionView setHidden:YES];
    }
    [self seekTimeline];
}


- (void)fitLiveWindowHeight {
    if(self.createMode == NvSSVideoCreateScaleHorizontal){
        self.liveWindowConstraintTop.constant = (SCREEN_WIDTH-SCREEN_WIDTH*9.0/16.0)/2;
        self.liveWindowConstraint1v1.shouldBeArchived = NO;
        self.liveWindowConstraint1v1.active = NO;
        self.liveWindowConstraint9v16.active = NO;
        [self.view removeConstraints:@[self.liveWindowConstraint1v1,self.liveWindowConstraint9v16]];
        [self.view addConstraints:@[self.liveWindowConstraint16v9,self.liveWindowConstraintLeft,self.liveWindowConstraintTop]];
    } else if (self.createMode == NvSSVideoCreateScaleVertical) {
        self.liveWindowConstraint1v1.active = NO;
        self.liveWindowConstraint16v9.active = NO;
        self.liveWindowConstraintLeft.active = NO;
        [self.view removeConstraints:@[self.liveWindowConstraint16v9,self.liveWindowConstraint1v1,self.liveWindowConstraintLeft]];
        [self.view addConstraints:@[self.liveWindowConstraint9v16,self.liveWindowConstraintTop]];
    } else {
        self.liveWindowConstraint16v9.active = NO;
        self.liveWindowConstraint9v16.active = NO;
        self.liveWindowConstraintTop.active = NO;
        [self.view removeConstraints:@[self.liveWindowConstraint16v9,self.liveWindowConstraint9v16,self.liveWindowConstraintTop]];
        [self.view addConstraints:@[self.liveWindowConstraint1v1,self.liveWindowConstraintLeft]];
    }
}

- (void)createControllView {
    [self.controllView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(self.selectView.mas_bottom);
        make.height.equalTo(@(self.bottomView.top_LL - self.selectView.bottom_LL - 10));
    }];
    //设置裁剪控件
    int64_t duration = [self.timeline duration];
    self.controllView.model = self.model;
    SaSliderModel *sliderModel = [SaSliderModel new];
    sliderModel.triminTimeStamp = _defaultTrinIn;
    sliderModel.trimoutTimeStamp = _defaultTrimOut;
    sliderModel.duration = duration;
    
    self.controllView.sliderModel = sliderModel;
    //设置缩略图
    if (self.createMode != NvSSVideoCreateScaleSquare) {
        self.controllView.stillImageHint = NO;
        [self.controllView startTime:0 duration:duration];
    }
}

- (void)initNavigationBarView {
    self.view.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.title = @"视频修改";
}

- (void)nv_getDefaultTrimTimeRange {
    _defaultTrinIn = 0;
    _defaultTrimOut = [NSNumber numberWithFloat:self.model.trimoutTimeStamp.floatValue-self.model.triminTimeStamp.floatValue];
    if ([_defaultTrimOut longLongValue] == 0 || _defaultTrimOut==nil) {
        _defaultTrimOut = [NSNumber numberWithLongLong:self.timeline.duration];
    }
    videoSpeed = [self.model.videoSpeed floatValue];
    
    _audioVolumn = self.model.audioVolumn;
}

- (void)nv_buildTimeLine {
    self.timeline = [Utils createTimeLine:self.createMode];
    NvsVideoTrack *videoTrack = [self.timeline appendVideoTrack];
    //add clip
    if(self.model.clipType ==  NvClipImage){
        if(self.model.imageDuration.intValue != 0) {
            self.nvsVideoClip = [videoTrack appendClip:self.model.clipPath trimIn:0 trimOut:self.model.imageDuration.intValue * NS_TIME_BASE];
        } else {
            self.nvsVideoClip = [videoTrack appendClip:self.model.clipPath trimIn:0 trimOut:4 * NS_TIME_BASE];
        }
    } else if (self.model.clipType ==  NvClipVideo) {
        if((self.model.triminTimeStamp.longLongValue == 0 && self.model.trimoutTimeStamp.longLongValue == 0)) {
            self.nvsVideoClip = [videoTrack appendClip:self.model.clipPath];
        } else {
            self.nvsVideoClip = [videoTrack appendClip:self.model.clipPath trimIn:self.model.triminTimeStamp.longLongValue trimOut:self.model.trimoutTimeStamp.longLongValue];
        }
        if (self.model.pan && self.model.scan) {
            [self.nvsVideoClip setPan:[self.model.pan floatValue] andScan:[self.model.scan floatValue]];
        }
        if (self.model.videoSpeed) {
            [self.nvsVideoClip changeSpeed:[self.model.videoSpeed floatValue]];
        }
    }
}

#pragma mark buttonClick
- (void)finishClick:(UIButton *)sender {
    if(self.clipType == NvClipVideo) {
        if([self.delegate respondsToSelector:@selector(didFinishSetVideoTrimIn:andTrimOut:sound:videoFx: videoSpeed:)]) {
            if ([_defaultTrimOut longLongValue]==0) {
                _defaultTrimOut = [NSNumber numberWithLongLong:[self.timeline duration]];
            }
            [self.delegate didFinishSetVideoTrimIn:_defaultTrinIn andTrimOut:_defaultTrimOut sound:_audioVolumn videoFx:self.filterArray[_selectedIndexPath.item] videoSpeed:[NSNumber numberWithFloat:videoSpeed]];
        }
    } else {
        if([self.delegate respondsToSelector:@selector(didFinishSetImageDuration:sound:videoFx:)]) {
            [self.delegate didFinishSetImageDuration:[NSNumber numberWithInt:_time] sound:_audioVolumn videoFx:self.filterArray[_selectedIndexPath.item]];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)close:(UIButton *)sender {
    if(self.clipType == NvClipVideo) {
        if([self.delegate respondsToSelector:@selector(didFinishSetVideoTrimIn:andTrimOut:sound:videoFx: videoSpeed:)]) {
            if ([_defaultTrimOut longLongValue]==0) {
                _defaultTrimOut = [NSNumber numberWithLongLong:[self.timeline duration]];
            }
            [self.delegate didFinishSetVideoTrimIn:_defaultTrinIn andTrimOut:_defaultTrimOut sound:_audioVolumn videoFx:self.filterArray[_selectedIndexPath.item] videoSpeed:[NSNumber numberWithFloat:videoSpeed]];
        }
    } else {
        if([self.delegate respondsToSelector:@selector(didFinishSetImageDuration:sound:videoFx:)]) {
            [self.delegate didFinishSetImageDuration:[NSNumber numberWithInt:_time] sound:_audioVolumn videoFx:self.filterArray[_selectedIndexPath.item]];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark Delgate
- (void)didChangeTime:(int)time {
    _time = time;
    self.durationLabel.text = [Utils stringWithTime:time];
    [self.progressSlider setMaximumValue:time*NS_TIME_BASE/self.playEnd];
    [self.nvsVideoClip changeTrimOutPoint:time*NS_TIME_BASE affectSibling:NO];
    self.playEnd = time * NS_TIME_BASE;
}

- (void)didChangeVolumn:(NSNumber *)audioVolumn {
    _audioVolumn = audioVolumn;
}

- (void)videoRange:(SAVideoRangeSlider*)videoRange didChangeLeftPosition:(CGFloat)leftPosition rightPosition:(CGFloat)rightPosition {
    _defaultTrinIn = [NSNumber numberWithLongLong:leftPosition];
    _defaultTrimOut = [NSNumber numberWithLongLong:rightPosition];
    float timestamp;
    if(videoRange.isLeft) {
        timestamp = leftPosition;
        [self startSeekTimeline:timestamp isLeft:YES];
    } else {
        timestamp = rightPosition;
        [self startSeekTimeline:timestamp isLeft:NO];
    }
}

- (void)startSeekTimeline:(float)timestamp isLeft:(BOOL)isLeft{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.streamingContext seekTimeline:self.timeline timestamp:timestamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];    });
    
    if (isLeft) {
        [self.progressSlider setValue:1.0*timestamp/self.timeline.duration animated:YES];
        [self updateCurLabel];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self seekTimeline];
        });
    } else {
        self.durationLabel.text = [Utils stringWithTime:1.0*timestamp/NS_TIME_BASE];
        [self.progressSlider setMaximumValue:timestamp/self.playEnd];
        self.playEnd = timestamp;
    }
}

#pragma mark - implement NvsLivewindow Player
- (void)updateCurLabel {
    self.curLabel.text = [Utils stringWithTime:self.progressSlider.value * (self.playEnd - self.playStart)/NS_TIME_BASE];
}

- (void)updateDurationLabel {
    self.durationLabel.text = [Utils stringWithTime:(self.playEnd - self.playStart)/NS_TIME_BASE];
}

- (void)updatePlayBtnState {
    [self.playBtn setImage: self.isPlaying? [UIImage imageFromBundle:@"player_stop"]: [UIImage imageFromBundle:@"player_play"]  forState:UIControlStateNormal];
}

-(void)setDefaultData{
    [self.filterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:self.model.videoFx]) {
            //设置CollectionViewCell的默认项
            self.selectedIndexPath = [NSIndexPath indexPathForItem:idx inSection:0];
            //设置显示CollectionViewCell位置
            [self.view layoutIfNeeded];
            [self.collectionView scrollToItemAtIndexPath:self.selectedIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            [self.collectionView reloadData];
            //设置默认滤镜特效
            [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:obj];
        }
    }];
    
    _time = self.model.imageDuration.intValue;
}

- (void)seekTimeline {
    if(self.isPlaying) {
        [self stop];
    }
    int flag = 0;
    
    int64_t seekPos = self.playStart + self.progressSlider.value * (self.playEnd - self.playStart);
    [self.streamingContext seekTimeline:self.timeline timestamp:seekPos videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:flag];
}

- (void)startPlaybackProgressTimer {
    NSTimeInterval timeInterval = 0.1;
    self.playbackProgressTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                                                  target:self
                                                                selector:@selector(handleProgressTimer:)
                                                                userInfo:nil
                                                                 repeats:YES];
}

- (void)handleProgressTimer:(NSTimer *)timer {
    self.progressSlider.value = ([self.streamingContext getTimelineCurrentPosition:self.timeline] - self.playStart) * 1.0/(self.playEnd - self.playStart);
    [self updateCurLabel];
}

- (void)play{
    int64_t startTime = self.playStart + self.progressSlider.value * (self.playEnd - self.playStart);
    int64_t endTime = self.playEnd;
    [self startPlaybackProgressTimer];
    
    [self.streamingContext playbackTimeline:self.timeline startTime:startTime endTime:endTime videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
    self.isPlaying = YES;
    [self updatePlayBtnState];
}

- (void)stop {
    [self.streamingContext stop];
    [self updateStopState];
}

- (void)updateStopState {
    [self.playbackProgressTimer invalidate];
    self.isPlaying = NO;
    [self updatePlayBtnState];
}

- (void)playAndStop {
    if(self.isPlaying)
        [self stop];
    else
        [self play];
}

#pragma mark - StreamingContext playing delegate
- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        [self.streamingContext seekTimeline:self.timeline timestamp:self.playStart videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
        self.progressSlider.value = _defaultTrinIn.floatValue/self.timeline.duration;
        [self updateCurLabel];
    }
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        [self updateStopState];
    }
}

#pragma mark - implement button response

- (IBAction)playBtnPressed:(id)sender {
    [self playAndStop];
}

- (void)progressSliderValueChanged:(id)sender {
    [self seekTimeline];
    [self updateCurLabel];
}

#pragma mark Getter

- (NvsStreamingContext *)streamingContext {
    return [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
}

- (UIView *)controllView {
    if (!_controllView) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        _controllView = [[myBundle loadNibNamed:@"ControllView" owner:self options:nil] lastObject];
        _controllView.delegate = self;
        if (IPHONE5) {
            [_controllView.VioceSliderView setHidden:YES];
            _controllView.imageSliderTopMargin.constant = 0;
            _controllView.videoSliderTopMargin.constant = 0;
            NSLog(@"121212121212");
        }
    }
    return _controllView;
}

- (UIView *)selectView {
    if (!_selectView) {
        _selectView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.width_LL+15, SCREEN_WIDTH, 40)];

        _selectView.backgroundColor = [UIColor whiteColor];
        
        CGFloat itemWidth = _selectView.height_LL - 10;
        NSArray *itemBars,*itemSelectedBars;
        if (self.clipType == NvClipImage) {
            itemBars = @[@"filter_n",@"edit_n"];
            itemSelectedBars = @[@"filter_s",@"edit_s"];
        } else {
            itemBars = @[@"filter_n",@"fast_n",@"edit_n"];
            itemSelectedBars = @[@"filter_s",@"fast_s",@"edit_s"];
        }
        
        for (int i = 0; i < itemBars.count; i++) {
            UIButton *itemBtn = [[UIButton alloc]init];
            itemBtn.frame = CGRectMake((itemWidth + 20)*i + 20, 5, itemWidth, itemWidth);
            [itemBtn setImage:[UIImage imageFromBundle:itemBars[i]] forState:UIControlStateNormal];
            [itemBtn setImage:[UIImage imageFromBundle:itemSelectedBars[i]] forState:UIControlStateSelected];
            
            itemBtn.tag = 100 + i;
            [itemBtn addTarget:self action:@selector(doSelectEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            [_selectView addSubview:itemBtn];
            
            if (i == 0) {
                
                UIView *gap = [[UIView alloc]init];
                gap.frame = CGRectMake(CGRectGetMinX(itemBtn.frame), itemBtn.bottom_LL+2, itemWidth,2);
                gap.backgroundColor = UIColorHexRGB(@"#3F80FF");
                gap.tag = 1000;
                [_selectView addSubview:gap];
            }
        }
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, _selectView.height_LL-1, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = [UIColor lightGrayColor];
        [_selectView addSubview:line];
    }
    return _selectView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.frame = CGRectMake(0, self.view.bottom_LL-64-44, SCREEN_WIDTH, 44);
        _bottomView.backgroundColor = [UIColor lightGrayColor];
        
        UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        finishBtn.frame = CGRectZero;
        finishBtn.frame = CGRectMake(_bottomView.width_LL/2+1, 0,  _bottomView.width_LL/2-0.5, 44);
        [finishBtn setBackgroundColor:UIColorHexRGB(@"#3F80FF")];
        [finishBtn setTitle:@"确定" forState:UIControlStateNormal];
        [finishBtn addTarget:self action:@selector(finishClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:finishBtn];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = CGRectMake(0, 0, _bottomView.width_LL/2-0.5, 44);
        [cancelBtn setBackgroundColor:UIColorHexRGB(@"#3F80FF")];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:cancelBtn];
    }
    return _bottomView;
}

- (UIView *)speedGoverningView {
    if (!_speedGoverningView) {
        _speedGoverningView = [[UIView alloc]initWithFrame:CGRectMake(0, self.selectView.bottom_LL, SCREEN_WIDTH, self.bottomView.top_LL-self.selectView.bottom_LL-10)];
        _speedGoverningView.backgroundColor = [UIColor whiteColor];
        DCSliderView *shapeView;
        if (!IPHONE5) {
                UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 20)];
                titleLabel.text = @"视频变速";
                titleLabel.textAlignment = NSTextAlignmentCenter;
                titleLabel.font = [UIFont systemFontOfSize:14];
                titleLabel.textColor = UIColorHexRGB(@"#999999");
                [_speedGoverningView addSubview:titleLabel];
                shapeView = [[DCSliderView alloc]initWithFrame:CGRectMake(20, titleLabel.bottom_LL+30, self.view.frame.size.width - 40, 30)];
        }else{
            shapeView = [[DCSliderView alloc]initWithFrame:CGRectMake(20, 30, self.view.frame.size.width - 40, 30)];
        }
        
        shapeView.shapeViewDelegate = self;
        [shapeView clickBtnWithIndex:[NSString stringWithFormat:@"%gX",videoSpeed]];
        [_speedGoverningView addSubview:shapeView];
    }
    return _speedGoverningView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        flowLayout.minimumLineSpacing = 1;
        flowLayout.itemSize = CGSizeMake(self.bottomView.top_LL-self.selectView.bottom_LL-25, self.bottomView.top_LL-self.selectView.bottom_LL-25);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.selectView.bottom_LL, SCREEN_WIDTH, self.bottomView.top_LL-self.selectView.bottom_LL-10) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

static NSString* captionStyleCellIdentifier = @"NvCapationStyleCell";

- (void)registerCaptionStyleCollectionViewCell {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.collectionView registerNib:[UINib nibWithNibName:captionStyleCellIdentifier bundle:myBundle]  forCellWithReuseIdentifier:captionStyleCellIdentifier];
}

- (void)clearTimeLine {
    if (self.timeline)
        [self.streamingContext removeTimeline:self.timeline];
    self.streamingContext = nil;
}

- (NSMutableArray *)filterArray {
    if (!_filterArray) {
        // 初始化特效tableview
        _filterArray = [NSMutableArray arrayWithObject:@"None"];
        // 获取全部内嵌采集视频特效的名称
        [_filterArray addObjectsFromArray:[self.streamingContext getAllBuiltinCaptureVideoFxNames]];
    }
    return _filterArray;
}


- (void)doSelectEvent:(UIButton *)sender {
    
    UIView *line = [self.view viewWithTag:1000];
    if (sender.tag != self.lastBtnTag) {
        UIButton *button = [self.selectView viewWithTag:self.lastBtnTag];
        [button setSelected:NO];
        self.lastBtnTag = sender.tag;
        [UIView animateWithDuration:0.2 animations:^{
            line.centerX_LL = sender.centerX_LL;
        }];
    }
    if (!sender.selected) {
        sender.selected = YES;
    }
    if (self.clipType == NvClipImage) {
        if (sender.tag == 100) {
            _isVideoFilter = true;
            _isVideoFast = false;
            _isVideoEdit = false;
        } else if (sender.tag == 101) {
            _isVideoEdit = true;
            _isVideoFast = false;
            _isVideoFilter = false;
        } else {
            _isVideoFast = true;
            _isVideoEdit = false;
            _isVideoFilter = false;
        }
    } else {
        if (sender.tag == 100) {
            _isVideoFilter = true;
            _isVideoFast = false;
            _isVideoEdit = false;
        } else if (sender.tag == 101) {
            _isVideoFast = true;
            _isVideoEdit = false;
            _isVideoFilter = false;
        } else {
            _isVideoEdit = true;
            _isVideoFast = false;
            _isVideoFilter = false;
        }
    }
    [self initSubViews];
}

#pragma mark UICollectionViewDataSource
- (NvCapationStyleCell *)cellAtIndexPath:(NSIndexPath *)indexPath {
    return (NvCapationStyleCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.filterArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvCapationStyleCell * cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:captionStyleCellIdentifier forIndexPath:indexPath];
    cell.coverImageView.image = [UIImage imageFromBundle:self.filterArray[indexPath.item]];
    NSString *filterName;
    if ([self.filterArray[indexPath.item] isEqualToString:@"Fresh"]) {
        filterName = @"清新";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Sage"]) {
        filterName = @"晨露";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Maid"]) {
        filterName = @"朝阳";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Mace"]) {
        filterName = @"青涩";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Lace"]) {
        filterName = @"鲜艳";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Mall"]) {
        filterName = @"暖阳";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Sap"]) {
        filterName = @"蓝调";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Sara"]) {
        filterName = @"日风";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Pinky"]) {
        filterName = @"樱花";
    } else if ([self.filterArray[indexPath.item] isEqualToString:@"Sweet"]) {
        filterName = @"甜美";
    } else {
        filterName = @"无";
    }
    cell.displayLabel.text = filterName;
    
    cell.selected = self.selectedIndexPath ? ([self.selectedIndexPath compare:indexPath] == NSOrderedSame) : NO;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if([self.selectedIndexPath isEqual:indexPath])
        return;
    if(self.selectedIndexPath){
        [self cellAtIndexPath:self.selectedIndexPath].selected = NO;
    }
    self.selectedIndexPath = indexPath;
    [self cellAtIndexPath:self.selectedIndexPath].selected = YES;
    
    self.curVideoFx = [self.timeline getFirstTimelineVideoFx];
    // 删除所有采集特效
    [self.timeline removeTimelineVideoFx:self.curVideoFx];
    
    if (![self.filterArray[indexPath.item] isEqualToString:@"None"]) {
        // 添加内置特效
        [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:self.filterArray[indexPath.item]];
    }

    
    [self seekTimeline];
}

#pragma mark  视频调速
- (void)onShapeViewDelegateEventWithString:(NSString *)str {
    
    [self.nvsVideoClip changeSpeed:str.floatValue];
    if (_isVideoFast) {
        videoSpeed = str.floatValue;
    }
    
    self.playEnd = self.nvsVideoClip.outPoint;
    [self updateDurationLabel];
}

@end
